package org.example.io.session;

import io.netty.channel.Channel;
import lombok.Data;
import org.example.io.protocol.Attributes;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class SessionUtil {

    private static final Map<String, Channel> sessionMap = new ConcurrentHashMap<>();

    public static Channel getChannel(String username) {
        return sessionMap.get(username);
    }

    public static ServerSession getSession(Channel channel) {
        return (ServerSession) channel.attr(Attributes.SERVER_SESSION).get();
    }

    public static boolean hasLogin(Channel channel) {
        return channel.hasAttr(Attributes.SERVER_SESSION);
    }

    public static void bindSession(ServerSession session, Channel channel) {
        sessionMap.put(session.getUserName(), channel);
        channel.attr(Attributes.SERVER_SESSION).set(session);
    }

    public static void unBindSession(Channel channel) {
        if (hasLogin(channel)) {
            ServerSession session = getSession(channel);
            sessionMap.remove(session.getUserName());
            channel.attr(Attributes.SERVER_SESSION).set(null);
        }
    }
}
